//
//  HzxqVC.swift
//  Auscultation
//
//  Created by 来 on 2020/12/8.
//

import UIKit

class HzxqVC: BaseVC {
    
    var id: String = ""
    // 1 没有新数据 2 有新数据
    var type: Int = 1;
    
    var top_view: UIImageView!
    
    var scrollView: UIScrollView!
    var yb_view: UIView!
    
    var tx: LGFLoginImageTitleView!
    var tx_i: UIImageView!
    var xm: LGFLoginImageTitleView!
    var xb: LGFLoginImageTitleView!
    var csrq: LGFLoginImageTitleView!
    var jhr: LGFLoginImageTitleView!
    var sjh: LGFLoginImageTitleView!
    var sfz: LGFLoginImageTitleView!
    var dq: LGFLoginImageTitleView!
    var xxdz: LGFLoginImageTitleView!
    
    var isEdit: Bool = false
    
    var collectionView: UICollectionView!
    
    var data: [String: Any]!
    
    var bc: UIButton!
    
    var dataArray: [[String: Any]] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        initUI()
        edit()
        getData()
        collectionView.mj_header = MJRefreshNormalHeader.init(refreshingTarget: self, refreshingAction: #selector(getData))
    }
    
    @objc func getData() {
        let paramet: [String: String] = [
            "encryptedData": "zFoamlSX95gBI7S05+e6HakuGltzhbckTNdkY0yZ2hU="
        ]
        EWERequest.lgf("patient/" + id, paramet, .get) { [weak self] (data) in
            self?.data = data as? [String : Any]
            self?.tx_i.lgf_setImage((data["avatar"] as? String) ?? "")
            self?.tx.lgf_Name = (data["avatar"] as? String) ?? ""
            self?.xm.text = (data["name"] as? String) ?? ""
            self?.xb.text = ((data["gender"] as? Int) ?? 0) == 1 ? "男" : "女"
            self?.xb.lgf_Name = ((data["gender"] as? Int) ?? 0).description
            self?.csrq.text = ((data["birthday"] as? Int) ?? 0).description.lgf_TimeStampToDate().lgf_TimeStr("yyyy-MM-dd")
            self?.csrq.lgf_Name = ((data["birthday"] as? Int) ?? 0).description
            self?.jhr.text = (data["guardian"] as? String) ?? ""
            self?.sjh.text = (data["phone"] as? String) ?? ""
            self?.sfz.text = (data["idCard"] as? String) ?? ""
            self?.dq.text = (data["address"] as? String) ?? ""
            self?.xxdz.text = (data["detailAddress"] as? String) ?? ""
            self?.dataArray = (data["screeningDtoList"] as? [[String : Any]]) ?? []
            self?.collectionView.reloadData()
            self?.endRefreshing()
        } _: { [weak self] (error) in
            SVProgressHUD.showError(error)
            self?.endRefreshing()
        }
    }
    
    func endRefreshing() {
        self.collectionView.mj_header?.endRefreshing()
    }
    
    // 编辑
    override func rightBtnSelect(_ sender: UIButton) {
        isEdit = !isEdit
        edit()
    }

    @objc func s_sx(_ sender: UITapGestureRecognizer) {
//        SxV().showIn(self.view) { (sxv, name, state) in
//            
//        }
    }
    
    @objc func s_bc() {

        if xm.textField.text!.lgf_IsBlank() {
            SVProgressHUD.showError("请填写姓名")
            return
        }
        if xb.textField.text!.lgf_IsBlank() {
            SVProgressHUD.showError("请选择性别")
            return
        }
        if jhr.textField.text!.lgf_IsBlank() {
            SVProgressHUD.showError("请填写监护人")
            return
        }
        if sjh.textField.text!.lgf_IsBlank() {
            SVProgressHUD.showError("请填写手机号")
            return
        }
        if !sjh.textField.text!.lgf_NSPredicate("^((13[0-9])|(14[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$") && !sjh.textField.text!.contains("****") {
            SVProgressHUD.showError("请填写正确手机号码")
            return
        }
        if csrq.textField.text!.lgf_IsBlank() {
            SVProgressHUD.showError("请选择出生日期")
            return
        }
//        if dq.textField.text!.lgf_IsBlank() {
//            SVProgressHUD.showError("请选择地区")
//            return
//        }
        
        let paramet: [String: String] = [
            "avatar" : tx.lgf_Name ?? "",
            "name" : xm.textField.text ?? "",
            "guardian" : jhr.textField.text ?? "",
            "phone" : sjh.textField.text ?? "",
            "idCard" : sfz.textField.text ?? "",
            "birthday" : (csrq.text + " 00:00:00"),
            "gender" : xb.lgf_Name ?? "",
            "address" : dq.textField.text ?? "",
            "detailAddress" : xxdz.textField.text ?? "",
            "hospitalId" : (self.data["hospitalId"] as? String) ?? "",
            "isDeleted" : (self.data["isDeleted"] as? String) ?? "",
            "createdBy" : (self.data["createdBy"] as? String) ?? "",
            "createdTime" : (self.data["createdTime"] as? String) ?? "",
            "updatedBy" : (self.data["updatedBy"] as? String) ?? "",
            "updatedTime" : (self.data["updatedTime"] as? String) ?? "",
            "lastTime" : Date().lgf_TimeStampString()
        ]
        EWERequest.lgf("patient/" + id, paramet, .put, JSONEncoding.default) { [weak self] (data) in
            SVProgressHUD.showSuccess("保存成功")
            self?.isEdit = false
            self?.edit()
            Timer.lgf_After(S: 0.5) {
                NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ReloadHzVC"), object: nil)
            }
        } _: { (error) in
            SVProgressHUD.showError(error)
        }
    }
    
    func edit() {
        tx.isUserInteractionEnabled = isEdit
        xm.isUserInteractionEnabled = isEdit
        tx.isUserInteractionEnabled = isEdit
        xb.isUserInteractionEnabled = isEdit
        csrq.isUserInteractionEnabled = isEdit
        jhr.isUserInteractionEnabled = isEdit
        sjh.isUserInteractionEnabled = isEdit
        sfz.isUserInteractionEnabled = isEdit
        dq.isUserInteractionEnabled = isEdit
        xxdz.isUserInteractionEnabled = isEdit
        if !isEdit {
            scrollView.snp.updateConstraints { (make) in
                make.bottom.equalTo(0)
            }
            rightText = "编辑  "
            getData()
        } else {
            scrollView.snp.updateConstraints { (make) in
                make.bottom.equalTo(-50)
            }
            rightText = "取消  "
        }
    }

}

extension HzxqVC : UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource , UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "Yb2CellPlayerStop"), object: nil)
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize  {
        return CGSize.init(width: UIDevice.lgf_ScreenW, height: 140)
    }
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.lgf_DequeueReusableCell(with: Yb2Cell.self, for: indexPath)
        cell.tzzx.text = (dataArray[indexPath.item]["no"] as? String) ?? ""
        cell.tw.text = "体位：" + ((dataArray[indexPath.item]["position"] as? String) ?? "")
        cell.phcd.text = "配合程度：" + ((dataArray[indexPath.item]["coordinate"] as? String) ?? "")
        cell.url = ((dataArray[indexPath.item]["screeningDetail"] as? [String: Any])?["wavPath"] as? String) ?? ""
        cell.initPlay()
        cell.allTime = cell.player.getAllTime(((dataArray[indexPath.item]["screeningDetail"] as? [String: Any])?["duration"] as? Int) ?? 0)
        cell.play_time.text = "00:00/" + cell.allTime
        let status = (dataArray[indexPath.item]["status"] as? Int) ?? 10
        if status == 10 {
            cell.status.text = "正在筛查"
            cell.status.textColor = UIColor.init(lgf_HexString: "8D969D")
        } else if status == 20 {
            cell.status.text = "筛查完成"
            cell.status.textColor = UIColor.init(lgf_HexString: "0F88F2")
        } else if status == 30 {
            cell.status.text = "筛查失败"
            cell.status.textColor = UIColor.init(lgf_HexString: "F27C0F")
        }
        return cell
    }
}
